using Acr.UserDialogs;
using RaceHFTools.Pages;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace RaceHFTools
{
    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();
            MainPage = new WelcomePage();
        }

        protected override async void OnStart()
        {
            string root = string.Empty;

            if (Device.RuntimePlatform == Device.Android)
            {
                bool perm_granted = false;
                do
                {
                    await Utils.Permission.RequestAndroidPermission();
                    if (await Utils.Permission.CheckAndroidPermission() == false)
                        Thread.CurrentThread.Abort();
                } while (perm_granted);

                root = @"/storage/emulated/0/RaceHF";
            }
            else if (Device.RuntimePlatform == Device.iOS)
            {
                root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            }
            Utils.File.SetRoot(root);

            if (!Directory.Exists(Utils.File.Root))
                Directory.CreateDirectory(Utils.File.Root);
            foreach (string file in Directory.GetFiles(Utils.File.Root))
            {
                if (Path.GetExtension(file) == ".bin")
                    File.Delete(file);
            }
            Utils.Log.Open(Utils.File.Log);

            Xamarin.Essentials.DeviceDisplay.KeepScreenOn = true;

            await Task.Delay(1000);
            MainPage = new NavigationPage(new ScanPage());
        }

        protected override void OnSleep()
        {

        }

        protected override void OnResume()
        {

        }
    }
}
